<?php
/**
 * gpa_new Description
 * @package
 * @name System
 * @filesource System.php
 * @author Meta Sanjaya
 */

include_once 'common.php';

class System extends Registry
{
    /**
     * @access public
     * @method __construct
     * @param void
     * @return void
     */
    public function  __construct()
    {
        parent::__construct();

        loadLibrary('Config');
        loadLibrary('URI');
        loadLibrary('Session');
        loadLibrary('Cookie');
        loadLibrary('Request');
        loadLibrary('Server');
    }

    /**
     * @access public
     * @static
     * @method run
     * @param void
     * @return void
     */
    public static function run()
    {
        $system = new System;
        $system->call(getInstance('uri')->getApp(), getInstance('uri')->getAct(), getInstance('uri')->getParam());
    }

    /**
     * @access public
     * @static
     * @method call
     * @param String $class
     * @param String $function
     * @return void
     */
    public function call($class, $function, $param=null)
    {
        if(!(@include_once __APP__ . $class . DIRECTORY_SEPARATOR . 'controller_' . $class . '.php')) {
            trigger_error("File $class.php Not Found!");
            exit;
        }

        $class = 'controller_' . $class;
        $this->app = new $class;

        if(!method_exists($this->app, $function)) {
            trigger_error("Method $function doesn't exists in Class $class!");
            exit;
        }
        
        $this->app->$function($param);
    }

    /**
     * @access public
     * @static
     */
    public static function load($class, $initiate=true, $contructor_param=null)
    {
        if($initiate) {
            System::set(strtolower($class), new $class($contructor_param));
        } else {
            include_once __search_in(__SYSTEM__, $class . '.php');
        }
    }

    public static function debug($class, $function)
    {

    }
}

function getInstance($instance) {
    return System::get($instance);
}

function loadLibrary($lib, $initiate=true, $contruct_param=null) {
    System::load($lib, $initiate, $contruct_param);
}

function getApps() {
    $apps = array();

    $dir = glob(__APP__ . '*', GLOB_ONLYDIR);

    foreach($dir as $path) {
        $apps[] = array(
            'path'=>$path,
            'name'=>str_replace(__APP__, '', $path)
        );
    }

    return $apps;
}
?>